Rotate List
Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.
题目大意:给定一个链表,右移k个位置
题目难度:Medium
import java.util.*;
/**
* Created by gzdaijie on 16/5/26
*/
public class Solution {
public ListNode rotateRight(ListNode head, int k) {
ListNode p = head, pre = null, last= null;
int len = 0;
while (p != null) {
len++;
last = p;
p = p.next;
}
if (len == 0) return head;
// 将链表分为 len - k,和k 2个部分
k = len - k % len;
p = head;
while (k-- > 0) {
pre = p;
p = p.next;
}
if (p != null && last != null) {
last.next = head;
pre.next = null;
}
return p == null ? head : p;
}
}